package com.team9.fitness.controller;

import com.team9.fitness.entity.UserProfile;
import com.team9.fitness.service.UserProfileService;
import com.team9.fitness.service.ZRDDSDataExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户个人信息管理控制器
 * 
 * 提供用户个人资料管理功能：
 * - 保存/更新个人信息：身高、体重、性别、生日等
 * - 查询个人信息：获取用户的详细个人资料
 * - 删除个人信息：清除用户的个人资料数据
 * 
 * 个人信息字段：
 * - 身高（cm）
 * - 体重（kg）
 * - 性别（男/女）
 * - 生日（日期）
 * - 个人简介（可选）
 */
@RestController
@RequestMapping("/api/user-profile")
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
@Slf4j
public class UserProfileController {

    @Autowired
    private UserProfileService userProfileService;

    @Autowired
    private ZRDDSDataExchangeService zrddsDataExchangeService;

    /**
     * 保存或更新用户个人信息
     */
    @PostMapping("/save")
    public ResponseEntity<Map<String, Object>> saveUserProfile(@RequestBody UserProfile userProfile) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 直接执行业务逻辑
            UserProfile savedProfile = userProfileService.saveOrUpdateUserProfile(userProfile);
            response.put("success", true);
            response.put("message", "个人信息保存成功");
            response.put("data", savedProfile);

            // 业务逻辑成功，发布数据到ZRDDS作为记录
            try {
                Map<String, Object> additionalData = new HashMap<>();
                additionalData.put("name", userProfile.getName());
                additionalData.put("height", userProfile.getHeight());
                additionalData.put("weight", userProfile.getWeight());
                additionalData.put("gender", userProfile.getGender());
                additionalData.put("birthday",
                        userProfile.getBirthday() != null ? userProfile.getBirthday().toString() : null);
                additionalData.put("des", userProfile.getDes());
                additionalData.put("location", userProfile.getLocation());
                additionalData.put("updateTime", java.time.LocalDateTime.now().toString());

                zrddsDataExchangeService.publishUserAction("UPDATE_PROFILE",
                        userProfile.getUserId(), userProfile.getName(), additionalData);
            } catch (Exception e) {
                log.warn("发布用户资料更新数据到ZRDDS失败", e);
                // 不影响业务逻辑
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("保存用户个人信息失败", e);
            response.put("success", false);
            response.put("message", "保存失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取用户个人信息
     */
    @GetMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> getUserProfile(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();

        try {
            UserProfile userProfile = userProfileService.getUserProfileByUserId(userId);
            if (userProfile != null) {
                response.put("success", true);
                response.put("data", userProfile);
            } else {
                response.put("success", true);
                response.put("data", null);
                response.put("message", "未找到个人信息");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户个人信息失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 删除用户个人信息
     */
    @DeleteMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> deleteUserProfile(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();

        try {
            userProfileService.deleteUserProfileByUserId(userId);
            response.put("success", true);
            response.put("message", "个人信息删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除用户个人信息失败", e);
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
}
